import os
class LogFile(object):
    MaxFlushLogSize = 1024 

    def __init__(self, directory, number):
        self.__number = number > 0 and number or 99999
        self.__directory = directory is not None and directory or "tmpdb"
        self.__size = 0
        LogFile.deleteFile(self.filePath())
        self.__file = open(self.filePath(), "w")

    def getNumber(self):
        return self.__number

    def filePath(self):
        return "%s-%d.redo.log" % (self.__directory, self.__number)

    def close(self):
        if self.__file is not None:
            self.__file.close()
            self.__file = None

    def append(self, binary):
        self.__size += len(binary)
        self.__file.write(binary)
        return self

    def size(self):
        return self.__size

    def delete(self):
        if self.__file is not None:
            self.close()
        LogFile.deleteFile(self.filePath())

    def hasFreeSpace(self, needSpace):
        return LogFile.MaxFlushLogSize - self.__size >= needSpace

    @staticmethod
    def deleteFile(filePath):
        if os.path.exists(filePath):
            os.remove(filePath)

import unittest
from LogNumber import LogNumber
class TestLogFile(unittest.TestCase):
    def testWrite(self):
        logFile = LogFile("abc", LogNumber().next())

        msg = "hello:world\n"
        self.assertTrue(logFile.hasFreeSpace(len(msg)*4))
        logFile.append(msg).append(msg).append(msg).append(msg)

        logFile.close()

    def testDelete(self):
        number = LogNumber() 
        logFile = LogFile("abc", number.next())

        msg = "hello:world\n"
        self.assertTrue(logFile.hasFreeSpace(len(msg)))
        logFile.append(msg)

        logFile.delete()

        logFile = LogFile("cde", number.next())
        msg = "hello:world\n"
        self.assertTrue(logFile.hasFreeSpace(len(msg)))
        logFile.append(msg)

        logFile.delete()
        
#end class


if __name__ == "__main__":
    suite = unittest.TestSuite([
        unittest.TestLoader().loadTestsFromTestCase(TestLogFile), 
    ])
    unittest.TextTestRunner(verbosity=2).run(suite)
